from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import os
from basic_monitoring.hostGroup.menu_click import click_monitoring_menu, click_host_group_menu, search_and_reset_by_group_names


def main():
    try:
        # 初始化浏览器（使用Service对象替代弃用的executable_path）
        service = webdriver.ChromeService(executable_path=r'D:\dev\chromedriver-win64\chromedriver.exe')
        driver = webdriver.Chrome(service=service)

        # 忽略SSL证书错误（适用于https://192.168.1.88这样的本地地址）
        options = webdriver.ChromeOptions()
        options.add_argument('--ignore-certificate-errors')
        driver = webdriver.Chrome(service=service, options=options)

        # 设置隐式等待（全局等待元素出现）
        driver.implicitly_wait(10)

        print("正在打开页面...")
        driver.get("https://192.168.1.88")

        # 使用显式等待确保元素加载完成
        print("等待登录表单加载...")
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.NAME, "username"))
        )

        # 查找元素
        username = driver.find_element(By.NAME, "username")
        password = driver.find_element(By.NAME, "password")

        # 操作元素
        username.send_keys("admin")
        password.send_keys("admin@123")
        print("提交登录信息...")
        password.send_keys(Keys.RETURN)

        # 等待页面跳转完成，满足 /homepage、maintaincentre/dashboardlist 或 maintaincentre/dashboard 任意一个即可
        print("等待登录成功...")
        try:
            WebDriverWait(driver, 15).until(
                lambda d: (
                    "/homepage" in d.current_url or
                    "maintaincentre/dashboardlist" in d.current_url or
                    "maintaincentre/dashboard" in d.current_url
                )
            )
            print("检测到已跳转到 /homepage、maintaincentre/dashboardlist 或 maintaincentre/dashboard 页面！")
        except Exception:
            print("未检测到 /homepage、maintaincentre/dashboardlist 或 maintaincentre/dashboard 页面，登录流程异常。")
            raise
        print("登录成功！页面标题:", driver.title)


        try:
            # 调用菜单点击逻辑
            click_monitoring_menu(driver)
            click_host_group_menu(driver)
            search_and_reset_by_group_names(driver)
        except Exception:
            screenshot_dir = os.path.join(os.getcwd(), "errImage")
            os.makedirs(screenshot_dir, exist_ok=True)
            screenshot_path = os.path.join(screenshot_dir, "对象群组错误.png")
            driver.save_screenshot(screenshot_path)
            print(f"错误截图已保存为: {screenshot_path}")
            print("错误截图已保存为 对象群组错误.png")
        finally:
            print("出现错误 关闭浏览器...")
            driver.quit()



    except Exception as e:
        print(f"执行过程中出错: {str(e)}")
        # 出错时截屏（确保有screenshots目录）
        # driver.save_screenshot("/errImage/error_screenshot.png")
        screenshot_dir = os.path.join(os.getcwd(), "errImage")
        os.makedirs(screenshot_dir, exist_ok=True)
        screenshot_path = os.path.join(screenshot_dir, "error_screenshot.png")
        driver.save_screenshot(screenshot_path)
        print(f"错误截图已保存为: {screenshot_path}")
        print("错误截图已保存为 error_screenshot.png")

    finally:
        # 确保无论是否出错都会关闭浏览器
        print("关闭浏览器...")
        print("即将关闭浏览器...")
        driver.quit()


if __name__ == '__main__':
    main()